package com.demo.connectdbtest.module.common.util;


import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;

/**
 * @author dsm
 * @date 2021/12/02
 * @description 统计在线时长
 */
public class TimeUtil {

    /**
     * 毫秒时间
     * Long类型时间转换成视频时长
     */
    public static String format(Long time) {
        if (time == null) {
            return null;
        } else {
            long hour = time / (60 * 60 * 1000);
            long minute = (time - hour * 60 * 60 * 1000) / (60 * 1000);
            long second = (time - hour * 60 * 60 * 1000 - minute * 60 * 1000) / 1000;
            return (hour == 0 ? "00" : (hour >= 10 ? hour : ("0" + hour))) + ":" + (minute == 0 ? "00" : (minute >= 10 ? minute : ("0" + minute))) + ":" + (second == 0 ? "00" : (second >= 10 ? second : ("0" + second)));
        }
    }

    /**
     * 时间为秒
     * Long类型时间转换成视频时长
     */
    public static String formatTime(Long time) {
        if (time == null) {
            return null;
        } else {
            long hour = time / (60 * 60);
            long minute = (time - hour * 60 * 60) / 60;
            long second = time - hour * 60 * 60 - minute * 60;
            return (hour == 0 ? "00" : (hour >= 10 ? hour : ("0" + hour))) + ":" + (minute == 0 ? "00" : (minute >= 10 ? minute : ("0" + minute))) + ":" + (second == 0 ? "00" : (second >= 10 ? second : ("0" + second)));
        }
    }

    /**
     * 日期增加-按天数增加
     *
     * @param date
     * @param dateNum
     * @return
     */
    public static Date addDate(Date date, Integer dateNum) {
        Calendar cl = Calendar.getInstance();
        cl.setTime(date);
        cl.add(Calendar.DATE, dateNum);
        return cl.getTime();
    }

    public static int diffDay(Long startTime, Long endTime) {
        long nd = 1000 * 24 * 60 * 60;
        long diff = endTime - startTime;
        long day = diff / nd;
        return (int) day;
    }

    /**
     * Long类型时间->转换成日期->转成要求格式的String类型
     */
    public static String fromLongToDate(String format, Long time) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = new Date(time);
        return sdf.format(date);
    }


    /**
     * 获取距离今天相差的天数
     */
    public static long getGapDay(Long startTime) {
        LocalDate startDate = new Date(startTime).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        return startDate.until(LocalDate.now(), ChronoUnit.DAYS);
    }

}
